package com.streaminggbs.common.utils;

import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * 字符串相关工具类
 * @author wangzhicheng
 *
 */
public class StringUtil {
	//自增数字，每次调用后自+1，确保唯一
	public static int INCREASE_NUM = 1;

	public static int getNum(){
		if(INCREASE_NUM > 9999){
			INCREASE_NUM = 1;
		}
		return INCREASE_NUM ++;
	}

	//验证空字符串
	public static boolean isEmpty(String str){
		if(str == null || str.trim().length() == 0 || str.trim().equalsIgnoreCase("null")){
			return true;
		}
		return false;
	}

	/**
	 * 判断一个集合或者map是否为空
	 * @param obj
	 * @return
	 */
	public static boolean isNotNullOrEmpty(Object obj){
		if(obj == null){
			return false;
		}

		if(obj instanceof Collection){
			return  !(((Collection) obj).isEmpty());
		}

		if(obj instanceof Map){
			return !(((Map) obj).isEmpty());
		}
		return true;
	}


	// 首字母转小写
	public static String toLowerCaseFirstOne(String s) {
		if (Character.isLowerCase(s.charAt(0))) {
            return s;
        }else {
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
	}

	// 首字母转大写
	public static String toUpperCaseFirstOne(String s) {
		if (Character.isUpperCase(s.charAt(0))) {
            return s;
        }else {
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
        }
	}

	/**
	 * 保留1位小数
	 */
	public static final float getOneFloat(float value)  {
		DecimalFormat fnum = new DecimalFormat("##0.0");
		return Float.parseFloat(fnum.format(value));
	}

	/**
	 * 保留2位小数
	 */
	public static final float getTwoFloat(float value)  {
		DecimalFormat fnum = new DecimalFormat("##0.00");
		return Float.parseFloat(fnum.format(value));
	}
	/**
	 * 保留2位小数
	 */
	public static final double getTwoDouble(double value)  {
		DecimalFormat fnum = new DecimalFormat("##0.00");
		return Double.parseDouble(fnum.format(value));
	}

	/**
	 * 保留2位小数
	 */
	public static String toDecimal2(Integer value)  {
		if(value == null){
			return "";
		}
		DecimalFormat format = new DecimalFormat("#0.00");
		return format.format(value * 1.0 / 100);
	}

	/**
	 * 字符串保留2位小数(为了处理金额)
	 */
	public static final String getTwoString(String value)  {
		if(value == null || "".equals(value) || "null".equals(value)){
			return "";
		}
		Pattern pattern = Pattern.compile("[0-9.]*");
		if(!pattern.matcher(value).matches()){
			return value;
		}
		if(value.indexOf(".") == -1){
			return value;
		}
		DecimalFormat fnum = new DecimalFormat("##0.00");
		String result = fnum.format(Double.parseDouble(value));
		if("0".equals(result.substring(result.length()-1))){
			result = result.substring(0,result.length()-1);
		}
		if("0".equals(result.substring(result.length()-1))){
			result = result.substring(0,result.length()-1);
		}
		if(".".equals(result.substring(result.length()-1))){
			result = result.substring(0,result.length()-1);
		}
		return result;
	}
	/**
	 * 保留4位小数
	 */
	public static final float getFourFloat(float value)  {
		DecimalFormat fnum = new DecimalFormat("##0.0000");
		return Float.parseFloat(fnum.format(value));
	}

	/**
	 * 去掉中文字符
	 * @param str
	 * @return
	 */
	public static String removeZh(String str){
		String regEx = "[\\u4e00-\\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("");
	}

	/**
	 * 留下中文开头的字符串
	 * @param str
	 * @return
	 */
	public static String subFistZh(String str){
		if(str == null || str ==""){
			return str;
		}
		String resultstr = str;
		String regEx = "[\\u4e00-\\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		for(int i=1;i<str.length();i++){
			Matcher m = p.matcher(str.substring(i-1, i));
			if(m.matches()){
				resultstr = str.substring(0, i);
			}else{
				break;
			}
		}
		return resultstr;
	}

	/**
	 * 去掉中文结尾的字符,但是如果全是中文则不处理
	 * @param str
	 * @return
	 */
	public static String removelastZh(String str){
		String oristr = str;
		if(str == null || str ==""){
			return str;
		}

		boolean notallzh = true; //是否全部为中文
		String regEx = "[\\u4e00-\\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		while(str.substring(0, str.length()-1).length() > 0){
			Matcher m = p.matcher(str.substring(str.length()-1, str.length()));
			if(m.matches()){
				str = str.substring(0, str.length()-1);
			}else{
				notallzh = false;
				break;
			}

		}
		if(notallzh){
			return oristr;
		}
		return str;
	}

	/**
	 * 判断车架号是不是L，不是L则只留下中文，否则去掉中文结尾的字符，并且去掉牌
	 * @param str,cjh车架号
	 * @return
	 */
	public static String zhFilter(String str,String cjh){
		if(str == null || str ==""){
			return str;
		}
		if(cjh == null || cjh ==""){
			return removelastZh(str);
		}
		str = str.replace("牌", "");
		if(cjh.startsWith("L") || cjh.startsWith("l")){
			return removelastZh(str);
		}else{
			return subFistZh(str);
		}
	}

	/**
	 * 根据身份证获取性别 1 男 2 女 9 未说明
	 * @param idnumber
	 * @return
	 */
	public static Integer getSex(String idnumber){
		if(idnumber.length() == 15){
			 Integer num = Integer.parseInt(idnumber.substring(idnumber.length()-1, idnumber.length()));
			 return num%2==0?2:1;
		}else if(idnumber.length() == 18){
			 Integer num = Integer.parseInt(idnumber.substring(idnumber.length()-2, idnumber.length()-1));
			 return num%2==0?2:1;
		}
		return 9;
	}

	/**
	 * 根据身份证获取年龄
	 * @param idnumber
	 * @return
	 */
	public static Integer getAge(String idnumber){
		 Integer num = Integer.parseInt(idnumber.substring(6, 10));
		 return Calendar.getInstance().get(Calendar.YEAR)- num;
	}

	/**
	 * 根据身份证获取年龄
	 * @param str
	 * @return
	 */
	public static boolean hasEnglish(String str){
		Pattern p = Pattern.compile("[a-zA-z]");
        if(p.matcher(str).find()){
        	return true;
        }else{
        	return false;
        }
	}

	/**
	 * 加权随机
	 * @param servers
	 * @return
	 */
	public static String getRandomByRate(Map<String, Integer> servers){
        if(servers == null || servers.size() == 0) {
			return null;
		}

        Integer sum = 0;
        Set<Map.Entry<String, Integer>> entrySet = servers.entrySet();
        Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();
        while(iterator.hasNext()){
            sum += iterator.next().getValue();
        }
        Integer rand = new Random().nextInt(sum) + 1;
        for(Map.Entry<String, Integer> entry : entrySet){
            rand -= entry.getValue();
            if(rand <=0){
                return entry.getKey();
            }
        }

        return null;
    }

	/**
	 * 生成4位数字符串，将不足4位的数字前端补0
	 */
	public static String fourPrefixZero(int num){
		StringBuilder sb = new StringBuilder();
		int maxLength = 4;//此处设置字符串的长度
		String numStr = String.valueOf(num);
		int numLength = numStr.length();
		if(numLength < maxLength){
			for(int i=0; i<maxLength-numLength; i++){
				sb.append("0");
			}
		}else{
			numStr = numStr.substring(numLength-maxLength);
		}
		sb.append(numStr);
		return sb.toString();
	}

	/**
	 * 生成5位数字符串，将不足5位的数字前端补0
	 */
	public static String fivePrefixZero(int num){
		StringBuilder sb = new StringBuilder();
		int maxLength = 5;//此处设置字符串的长度
		String numStr = String.valueOf(num);
		int numLength = numStr.length();
		if(numLength < maxLength){
			for(int i=0; i<maxLength-numLength; i++){
				sb.append("0");
			}
		}else{
			numStr = numStr.substring(numLength-maxLength);
		}
		sb.append(numStr);
		return sb.toString();
	}

	/**
	 * 生成三位随机数
	 */
	public static String threeMathRandom(){
		int maxLength = 3;
		int random1 = (int) (Math.random() * Math.pow(10,maxLength) * 0.9 + Math.pow(10,maxLength-1));
		String random = String.valueOf(random1);
		return random;
	}

	/**
	 * 生成五位随机数
	 */
	public static String fiveMathRandom(){
		int maxLength = 5;
		int random1 = (int) (Math.random() * Math.pow(10,maxLength) * 0.9 + Math.pow(10,maxLength-1));
		String random = String.valueOf(random1);
		return random;
	}

	/**
	 * 生成六位随机数
	 */
	public static String sixMathRandom(){
		int maxLength = 6;
		int random1 = (int) (Math.random() * Math.pow(10,maxLength) * 0.9 + Math.pow(10,maxLength-1));
		String random = String.valueOf(random1);
		return random;
	}

	/**
	 * 生成八位随机数
	 */
	public static String eightMathRandom(){
		int maxLength = 8;
		int random1 = (int) (Math.random() * Math.pow(10,maxLength) * 0.9 + Math.pow(10,maxLength-1));
		String random = String.valueOf(random1);
		return random;
	}

	/**
	 * 去除字符串前面的0
	 */
	public static String cutZeroForStr(String str){
		int len = str.length();// 取得字符串的长度
        int index = 0;// 预定义第一个非零字符串的位置
        int n = 0;// 判断0的个数

        char strs[] = str.toCharArray();// 将字符串转化成字符数组
        for (int i = 0; i < len; i++) {
            if ('0' != strs[i]) {
                index = i;// 找到非零字符串并跳出
                break;
            }else{
            	n++;
            }
        }
        String strLast = "";
        if(n < len){
        	strLast = str.substring(index, len);// 截取字符串
        }
        return strLast;
	}

	/**
	 * 元转分
	 */
	public static final String chageYuanToFen(String value)  {
		if(value == null || value.trim().length()==0 || "null".equals(value)) {
			return null;
		}
		Double yuan = Double.parseDouble(value);
		Double fen = yuan*100;
		return String.valueOf(Math.round(fen)) ;
	}

	/**
	 * 分转元
	 */
	public static final String chageFenToYuan(String value)  {
		if(value == null || value.trim().length()==0 || "null".equals(value)) {
			return null;
		}
		Double yuan = Double.parseDouble(value);
		return String.valueOf(getTwoDouble(yuan)/100) ;
	}

	public static String stringNullToEmpty(String str){
		if(str == null){
			str = "";
		}
		return str;
	}

    /**
     * 如果字符串首尾不是数字、字母、中文，直接去掉
     * @param str
     * @return
     */
    public static String strRemoveFirstAndLastSymbol(String str){
        if(isEmpty(str)){
            return "";
        }
        str = str.trim();//去掉首尾空格
        String originalStr = str;//这里给一个对象存储去除字符之前的原始的字符串，用于比较是否需要递归

        Pattern pattern = Pattern.compile("^[a-zA-Z0-9\u4e00-\u9fa5]+$");//字母、数字、中文
        //取第一个字符
        if(!isEmpty(str)){
            String firstStr = str.substring(0,1);
            Matcher matcherFirst = pattern.matcher(firstStr);
            if(!matcherFirst.matches()){
                str = str.substring(1);
            }
        }
        //取最后一个字符
        if(!isEmpty(str)){
            String lastStr = str.substring(str.length() - 1);
            Matcher matcherFirst = pattern.matcher(lastStr);
            if(!matcherFirst.matches()){
                str = str.substring(0, str.length() - 1);
            }
        }

        if(originalStr.length() != str.length()){
            return strRemoveFirstAndLastSymbol(str);
        }else{
            return str;
        }
    }

	public static void main(String[] args) {

	}

}
